package com.bwie.common.handler;

import com.bwie.common.exception.BizException;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {


    /**
     * 业务异常处理器
     */
    @ExceptionHandler({BizException.class})
    public Result bizExceptionHandler(BizException bizException) {
        log.error("业务异常，异常信息：{}", bizException.getMessage());
        return Result.error(bizException.getMessage());
    }

    /**
     * 参数验证不通过异常处理器
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException mane) {
        // 获取参数验证失败的错误信息
        BindingResult bindingResult = mane.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        // 拼接错误信息
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(error -> {
            String defaultMessage = error.getDefaultMessage();
            stringBuilder.append(defaultMessage + ";");
        });
        String allErrMsg = stringBuilder.toString();
        log.error("参数验证不通过异常，错误信息：{}", allErrMsg);
        return Result.error(allErrMsg);
    }

}
